package cn.edu.lingnan.util;

import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

public class XmlParser {
    //输入参数：待解析的XML文件，输出参数：HashMap集合
    public static HashMap<String,String> parse(String _xmlFileName){
        HashMap<String,String> hm=new HashMap<>();

        SAXParser saxParser = null;
        try {
            //实例化一个SAXParserFactory对象：
            SAXParserFactory factory = SAXParserFactory.newInstance();

            //通过factory获得一个SAXParser对象，即SAX解析器：
            saxParser = factory.newSAXParser();

            //saxParser对象调用parse方法解析XML文件：
            File file = new File(_xmlFileName);
            XmlHandler xmlHandler = new XmlHandler();
            saxParser.parse(file,xmlHandler);
            hm = xmlHandler.getHm();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return hm;
    }
}
